package edu.nctu.csie.jichang.tw2cn;

import java.io.File;
import java.io.IOException;

import edu.nctu.csie.jichang.tw2cn.util.Ascii2Native;
import edu.nctu.csie.jichang.tw2cn.util.FileUtil;

public class Main {
	
	private static final String ZH_TW = "zh_TW";
	private static final String ZH_CN = "zh_CN";
	
	public static void main(String[] path) throws Exception {
		String tPath      = getPath(path);
		boolean tShowFile = getShow(path);
		File tPathFile = new File(tPath);
		if(tPathFile.isDirectory()){
			for (File f : tPathFile.listFiles()) {
				handleFileTranslate(tShowFile, f);
			}
		}else{
			handleFileTranslate(tShowFile, tPathFile);
		}
		System.out.println("Transform finish ...");
	}

	private static void handleFileTranslate(boolean tShowFile, File f)throws IOException {
		if(f.getName().indexOf(ZH_TW)>0){
			System.out.println("handle file = " + f.getName());
			String tString = FileUtil.readFileToString(f);
			tString = Ascii2Native.ascii2Native(tString);
			if(tShowFile){
				FileUtil.writeStringToFile(tString, new File(f.getAbsolutePath()+".native"));
			}
			tString = Translate.doTranslate(tString);
			if(tShowFile){
				FileUtil.writeStringToFile(tString, new File(f.getAbsolutePath().replaceAll(ZH_TW, ZH_CN)+".native"));
			}
			tString = Ascii2Native.native2Ascii(tString);
			FileUtil.writeStringToFile(tString, new File(f.getAbsolutePath().replaceAll(ZH_TW, ZH_CN)));
		}
	}

	private static boolean getShow(String[] path)  throws Exception {
		try {
			return ("true".equalsIgnoreCase(path[1]) || "1".equalsIgnoreCase(path[1]));
		} catch (Exception e) {
		}
		return false;
	}

	private static String getPath(String[] path) throws Exception  {
		if(path == null || path.length<=0){
			throw new Exception("please input file path");
		}
		if(!new File(path[0]).exists()){
			throw new Exception("File or Directory is not exist");
		}
		return path[0];
	}
}
